/**
 * 注意：
 *  1，scrollView/view组件需要添加widget组件，并设置left,top,right,bottom为0，
 *     保证滚动试图和父节点宽高保持一致
 *  2, content添加Layout组件，并设置Type:VERTLCAL， Resize Mode：CONTAINER
 */

const { TOUCH_CANCEL, TOUCH_START, TOUCH_END } = cc.Node.EventType;

cc.Class({
    extends: cc.Component,

    properties: {
        itemTip: cc.Node, // listItem节点，随业务自定义
        scrollView: cc.ScrollView,
        coverNode: cc.Node, // 覆盖层
        isLisenEvent: true, // 是否注册监听触摸事件
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        if(this.itemTip){
            this.itemTip.parent = null;
        }
        
        if(this.isLisenEvent){
            this.initEvent()
            if(this.coverNode){
                this.coverNode.active = false
            }
        }else{
            if(this.coverNode){
                this.coverNode.active = true;
                // 禁掉scrollView的触摸scroll事件
                this.coverNode.on(TOUCH_START,function(){
                    console.log('cover TOUCH_START')
                })
            }
        }
    },

    start () {
        this._index = 1;
        this.addItem();
        this.changeHandler();
    },

    // update (dt) {},

    // 初始化事件监听
    initEvent(){
        this.scrollView.node.on(TOUCH_START, () => {
            console.log('start')
            this.unschedule(this.addItem) // 手指按下停止滚动
            this._isStartScroll = false;
        },this, true)
        this.scrollView.node.on(TOUCH_CANCEL, this.reStartHandler, this)
        this.scrollView.node.on(TOUCH_END, this.reStartHandler, this)
    },

    // 添加数据并滚动
    changeHandler(){
        console.log('changeHandler')
        if(this.scrollView && this.itemTip){
            this.unschedule(this.addItem)
            this.schedule(this.addItem, 1)
            this._isStartScroll = true; 
        }
    },

    addItem(){
        if(!this.scrollView || !this.itemTip){
            console.warn('缺少node参数')
            return
        }
        let item = cc.instantiate(this.itemTip);
        item.parent = this.scrollView.content;
        item.getComponent(cc.Label).string = '杨紫' + this._index;
        this.scheduleOnce(() => {
            this.scrollView.scrollToBottom(0.5, false)
        }, 0.1)

        this._index++
    },

    // 重启滚动
    reStartHandler(){
        if(!this._isStartScroll){
            this._isStartScroll = true;
            this.unschedule(this.changeHandler)
            this.scheduleOnce(this.changeHandler, 0.3)
        }
    }
});
